/**
 * 消息通知
 * @author linfeng
 * @since 2020/05/22
 */
let tableRender
let reloadUnreadCount

layui.define(['index', 'form', 'table', 'laypage', 'layedit', 'laydate'], function (exports) {
    var $ = layui.$;
    var form = layui.form;
    var layer = layui.layer;
    var table = layui.table;
    var laypage = layui.laypage;
    var layedit = layui.layedit;

    form.render();

    tableRender = () => {
        const page = {
            limit: 50,
            limits: [50, 100, 150],
            curr: 1,
        }
        const cols = [
            {
                field: 'content', title: '内容', unresize: true, align: 'left', templet: function (d) {
                    const params = JSON.parse(d.params);
                    return '<zmn style="font-weight: bold" onclick="markAsReadAndJump(\'' + d.recordId + '\',\'' + d.readStatus + '\',\'' + params.url + '\',\'' + params.title + '\')">' + params.title + '</zmn><br><zmn onclick="markAsReadAndJump(\'' + d.recordId + '\',\'' + d.readStatus + '\',\'' + params.url + '\',\'' + params.title + '\')">' + d.content + '</zmn>'
                },
            },
            {
                field: 'createTime',
                title: '时间',
                unresize: true,
                align: 'center',
                width: 180,
                templet: "<div>{{layui.util.toDateString(d.createTime)}}</div>"
            },
        ];
        if (json.flag === 2) {
            cols.push({
                field: '操作',
                title: '操作',
                unresize: true,
                align: 'left',
                width: 200,
                templet: '<div><input lay-filter="markAsRead" lay-skin="primary" type="checkbox" name="handle" id="markAsRead" value="{{d.recordId}}"><zmn>标记为已处理</zmn></div>'
            })
        }
        const renderData = (data) => {
            laypage.render({
                elem: 'pageDiv',
                count: data.data.totalCount,
                limit: page.limit,
                limits: page.limits,
                curr: page.curr,
                layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip'],
                jump: function (obj, first) {
                    if (!first) {
                        page.curr = obj.curr
                        page.limit = obj.limit
                        loadData(page.curr, page.limit)
                    }
                }
            })
            table.render({
                elem: '#zmn-table',
                cols: [cols],
                height: 'full-152',
                data: data.data.items,
                limit: page.limit,
                limits: page.limits,
            })
        }
        const loadData = (pageIndex, pageSize) => {
            $.ajax({
                type: "POST",
                url: ZMN_URL_ENV + "gateway-api.xiujiadian.com/mcs/api/plat/listPageByQuery",
                contentType: "application/json",
                dataType: "json",
                data: JSON.stringify({
                    body: {
                        query: {
                            objectId: `${json.staffId}`,
                            receiverType: 70,
                            messageType: 150,
                            readStatus: json.flag === 1 ? null : 1,
                            pageIndex: pageIndex,
                            pageSize: pageSize,
                        }
                    }
                }),
                success: function (result) {
                    renderData(result)
                }
            })
        }
        loadData(page.curr, page.limit)
    }
    tableRender()

    reloadUnreadCount = () => {
        $.ajax({
            type: "POST",
            url: ZMN_URL_ENV + "gateway-api.xiujiadian.com/mcs/api/plat/countByQuery",
            contentType: "application/json",
            dataType: "json",
            data: JSON.stringify({
                body: {
                    query: {
                        objectId: `${json.staffId}`,
                        receiverType: 70,
                        messageType: 150,
                        readStatus: 1,
                    }
                }
            }),
            success: function (result) {
                if (result.status === 200) {
                    if (result.data === 0) {
                        $(top.window.document.body).find('#unReadMsgCount').hide();
                    } else if (result.data <= 99) {
                        $(top.window.document.body).find('#unReadMsgCount').text(result.data);
                        $(top.window.document.body).find('#unReadMsgCount').show();
                    } else {
                        $(top.window.document.body).find('#unReadMsgCount').text("99+");
                        $(top.window.document.body).find('#unReadMsgCount').show();
                    }
                }
            }
        })
    }

    const markAsRead2 = (recordId) => {
        $.ajax({
            type: "POST",
            url: ZMN_URL_ENV + "gateway-api.xiujiadian.com/mcs/api/plat/modifyRead",
            contentType: "application/json",
            dataType: "json",
            data: JSON.stringify({
                body: {
                    dio: {
                        objectId: `${json.staffId}`,
                        recordId: recordId
                    }
                }
            }),
            success: function (result) {
                tableRender()
                reloadUnreadCount()
            }
        })
    }

    form.on("checkbox(markAsRead)", function (obj) {
        // $(obj).attr("disabled", true);
        let id = obj.elem.value;
        markAsRead2(id);
    });

    //对外暴露的接口
    exports('msg_list_js', {});
});

function markAsRead(id) {
    var $ = layui.$;
    let url = "/push/inner/read.action";
    $.ajax({
        type: "POST", url: url,
        dataType: "json", data: {innerId: id, status: 2},
        success: function (json) {
            if (json.status == 200) {
                let countUrl = "/push/inner/unReadMsgCount.action";
                $.ajax({
                    type: "POST", url: countUrl,
                    dataType: "json", data: {},
                    success: function (items) {
                        if (items.status == 200) {
                            if (items.data == 0) {
                                $(top.window.document.body).find('#unReadMsgCount').hide();
                            } else if (items.data <= 99) {
                                $(top.window.document.body).find('#unReadMsgCount').text(items.data);
                                $(top.window.document.body).find('#unReadMsgCount').show();
                            } else {
                                $(top.window.document.body).find('#unReadMsgCount').text("99+");
                                $(top.window.document.body).find('#unReadMsgCount').show();
                            }
                        }
                    }
                });
                zmnPage.reload(json.data, 1000);
            } else {
                layer.msg(json.data);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
        }
    });
}

function markAsReadAndJump(recordId, readStatus, url, title) {
    if (json.flag === 2 && readStatus === '1') {
        layui.$.ajax({
            type: "POST",
            url: ZMN_URL_ENV + "gateway-api.xiujiadian.com/mcs/api/plat/modifyRead",
            contentType: "application/json",
            dataType: "json",
            data: JSON.stringify({
                body: {
                    dio: {
                        objectId: `${json.staffId}`,
                        recordId: recordId
                    }
                }
            }),
            success: function (result) {
                tableRender()
                reloadUnreadCount()
                zmnLayUtil.openTabsPageCustom(parent, url, title);
            }
        });
    } else {
        zmnLayUtil.openTabsPageCustom(parent, url, title);
    }
}
